package com.example.yichuangyun.mvvm.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yichuangyun.R;
import com.example.yichuangyun.databinding.ItemContactWayBinding;
import com.example.yichuangyun.dialog.ContactWayPopWindow;
import com.example.yichuangyun.model.contacts.ContactWayModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UiUtils;

import java.util.ArrayList;
import java.util.List;

public class ContactsPhoneAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private List<ContactWayModel> data;
    private final OnPhoneButtonChangeListener onPhoneButtonChangeListener;

    public ContactsPhoneAdapter(Context context, List<ContactWayModel> data, OnPhoneButtonChangeListener onPhoneButtonChangeListener) {
        this.context = context;
        this.data = data;
        this.onPhoneButtonChangeListener = onPhoneButtonChangeListener;
    }

    public void onRefresh(List<ContactWayModel> mList) {
        if (mList != null) {
            if (data == null) {
                data = new ArrayList<>();
            }
            this.data.clear();
            this.data.addAll(mList);
            notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemContactWayBinding itemContactWayBinding = ItemContactWayBinding.inflate(LayoutInflater.from(context), parent, false);
        return new ContactWayViewHolder(itemContactWayBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ContactWayViewHolder) {
            ContactWayViewHolder contactWayViewHolder = (ContactWayViewHolder) holder;
            ContactWayModel model = data.get(position);
            contactWayViewHolder.binding.ivAddInfo.setBackgroundResource(position == 0 ? R.drawable.shape_add_number : R.drawable.shape_del_bg_bbc2cb);
            contactWayViewHolder.binding.ivAddInfo.setImageResource(position == 0 ? R.mipmap.icon_add_write : R.mipmap.icon_reduce_write);
            contactWayViewHolder.binding.tvStar.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
            contactWayViewHolder.binding.ivDown.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
            contactWayViewHolder.binding.line.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
            contactWayViewHolder.binding.tvContactWay.setText(UiUtils.getContactTypeName(model.getType()));

            contactWayViewHolder.binding.ivAddInfo.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                if (position == 0) {
                    data.add(new ContactWayModel(1));
                } else {
                    data.remove(model);
                }
                notifyDataSetChanged();
                onPhoneButtonChangeListener.onPhoneChangeListener(data);
            });

            contactWayViewHolder.binding.rlContactWay.setEnabled(position != 0);
            contactWayViewHolder.binding.rlContactWay.setOnClickListener(v -> {
                CommonUtil.closeKeyboard((Activity) context);
                ContactWayPopWindow popWindow = new ContactWayPopWindow(context) {
                    @Override
                    public void sure(String type) {
                        if (!type.equals(contactWayViewHolder.binding.tvContactWay.getText().toString())) {
                            contactWayViewHolder.binding.etInfo.setText("");
                            model.setInfo("");
                        }
                        switch (type) {
                            case "手机号码":
                                model.setType(1);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
                                break;
                            case "微信":
                                model.setType(2);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_TEXT);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                                break;
                            case "QQ":
                                model.setType(3);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
                                break;
                            case "邮箱":
                                model.setType(4);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                                break;
                            case "固定电话":
                                model.setType(5);
                                contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                                contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});
                                break;
                        }
                        contactWayViewHolder.binding.tvContactWay.setText(type);
                        onPhoneButtonChangeListener.onPhoneChangeListener(data);
                    }
                };
                popWindow.showPopupWindow(contactWayViewHolder.binding.tvContactWay);
            });

            //1、为了避免TextWatcher在第2步被调用，提前将他移除。
            if (contactWayViewHolder.binding.etInfo.getTag() instanceof TextWatcher) {
                contactWayViewHolder.binding.etInfo.removeTextChangedListener((TextWatcher) (contactWayViewHolder.binding.etInfo.getTag()));
            }

            switch (model.getType()) {
                case 1:
                    contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                    contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
                    break;
                case 2:
                    contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_TEXT);
                    contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                    break;
                case 3:
                    contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                    contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
                    break;
                case 4:
                    contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
                    contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                    break;
                case 5:
                    contactWayViewHolder.binding.etInfo.setInputType(InputType.TYPE_CLASS_NUMBER);
                    contactWayViewHolder.binding.etInfo.setFilters(new InputFilter[]{new InputFilter.LengthFilter(12)});
                    break;
            }
            // 第2步：移除TextWatcher之后，设置EditText的Text。
            contactWayViewHolder.binding.etInfo.setText(model.getInfo());

            TextWatcher watcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                }

                @Override
                public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable editable) {
                    model.setType(UiUtils.getContactType(contactWayViewHolder.binding.tvContactWay.getText().toString()));
                    model.setInfo(TextUtils.isEmpty(editable.toString()) ? "" : editable.toString());
                    onPhoneButtonChangeListener.onPhoneChangeListener(data);
                }
            };
            contactWayViewHolder.binding.etInfo.addTextChangedListener(watcher);
            contactWayViewHolder.binding.etInfo.setTag(watcher);

            contactWayViewHolder.binding.etInfo.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus) {
                    switch (model.getType()) {
                        case 1:
                            if (model.getInfo() != null) {
                                if (model.getInfo().length() < 11 || !model.getInfo().startsWith("1")) {
                                    ToastHelper.show(context.getString(R.string.please_input_correct_phone));
                                    return;
                                }
                            }
                            break;
                        case 4:
                            if (!CommonUtil.isEmail(contactWayViewHolder.binding.etInfo.getText().toString())) {
                                ToastHelper.show(context.getString(R.string.please_input_correct_email));
                                contactWayViewHolder.binding.etInfo.setText("");
                            }
                            break;
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    static class ContactWayViewHolder extends RecyclerView.ViewHolder {

        ItemContactWayBinding binding;

        public ContactWayViewHolder(ItemContactWayBinding itemContactWayBinding) {
            super(itemContactWayBinding.getRoot());
            binding = itemContactWayBinding;
        }
    }

    public interface OnPhoneButtonChangeListener {
        void onPhoneChangeListener(List<ContactWayModel> list);
    }
}
